package com.example.bleuesprit.parkAndroidClient;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnMapLoadedListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.example.bleuesprit.parkAndroidClient.global.GlobalArgs;
import com.example.bleuesprit.parkAndroidClient.net.ExampleClient;
import com.example.bleuesprit.parkAndroidClient.net.NetUtil;

import org.java_websocket.drafts.Draft_17;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.URI;
import java.util.ArrayList;

public class MainActivity extends Activity implements LocationSource,AMapLocationListener,OnMapLoadedListener,OnCameraChangeListener,OnMarkerClickListener
{
    private boolean debug=false;

    NotificationManager nm;
    String userAccount=null;

    //地图数据
    private MapView mapView;
    public static AMap aMap;
    private LocationManagerProxy mLocationManagerProxy;
    private OnLocationChangedListener mListener;
    //服务器返回结果
    private JSONArray receiveParksJA;

    //侧边栏导航数据
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private String[] mActivityList={"账户信息","订单信息","停车场搜索"};
    private String[] mActivityClassList={"com.example.bleuesprit.parkAndroidClient.AboutMeActivity",
            "com.example.bleuesprit.parkAndroidClient.OrdersActivity","com.example.bleuesprit.parkAndroidClient.SearchParkByNameActivity"
    };


    Handler mainActivityHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0x123) {
                // 登录信息返回结果

                Log.i("MainActivity",msg.getData().getString("result"));
                try {
                    JSONObject jsonObject = new JSONObject(msg.getData().getString("result"));

                    Toast.makeText(MainActivity.this, jsonObject.getString("total"), Toast.LENGTH_SHORT).show();

                    int reciveParksCount = Integer.valueOf(jsonObject.getString("total"));
                    Log.i("MainActivity", "get parks count" + reciveParksCount);
                    ArrayList<MarkerOptions> markerOptionlst = new ArrayList<MarkerOptions>();
                    markerOptionlst.ensureCapacity(reciveParksCount);
                    receiveParksJA = new JSONArray(jsonObject.getString("parkData"));

                    for (int i = 0; i < reciveParksCount; i++) {
                        JSONObject temp = receiveParksJA.getJSONObject(i);
                        MarkerOptions tempMarkerOptions = new MarkerOptions();
                        tempMarkerOptions.title(Integer.toString(i));

                        //  Log.i("MainActivity",tempMarkerOptions.getTitle());
                        tempMarkerOptions.position(new LatLng(Double.valueOf(temp.getString("latitude")), Double.valueOf(temp.getString("longitude"))));
                        tempMarkerOptions.draggable(false);
                        tempMarkerOptions.icon(BitmapDescriptorFactory
                                .defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

                        markerOptionlst.add(tempMarkerOptions);
                    }
                     aMap.addMarkers(markerOptionlst, false);

                }catch (JSONException e){
                    e.printStackTrace();
                }

            }
            else if(msg.what==0x130)//websocket
            {
                try {
                    JSONObject jsonObject=new JSONObject(msg.getData().getString("result"));
                    Log.i("MainActivity","websocket"+jsonObject.toString());

                    String op=jsonObject.getString("op");
                    switch (op)
                    {

                        case "orderAccept":
                            Intent intent=new Intent(MainActivity.this,OrdersActivity.class);
                            PendingIntent pi=PendingIntent.getActivity(MainActivity.this,0,intent,0);
                            Notification notify=new Notification.Builder(MainActivity.this)
                                    .setAutoCancel(true)
                                    .setTicker("订单新消息")
                                    .setSmallIcon(R.drawable.notify)
                                    .setContentTitle("订单接受")
                                    .setContentText("您有新订单已经接受")
                                    .setWhen(System.currentTimeMillis() + 1000)
                                    .setContentIntent(pi)
                                    .build();

                            nm.notify(0x111,notify);
                            break;
                        default:
                            break;

                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };
//onCamerachangeLisener
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }



    private double lastLongitude=0;
    private double lastLatitude=0;
    //private Calendar last
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        if(Math.abs(cameraPosition.target.longitude-lastLongitude)<0.0005&&
                Math.abs(cameraPosition.target.latitude-lastLatitude)<0.0005)
        {
            return;
        }

        lastLongitude=cameraPosition.target.longitude;
        lastLatitude=cameraPosition.target.latitude;
        Log.i("MainActivity","onCameraChangeFinish");
        JSONObject searchParkingMessage=new JSONObject();
        try {
            searchParkingMessage.put("longitude", Double.toString(cameraPosition.target.longitude));
            searchParkingMessage.put("latitude", Double.toString(cameraPosition.target.latitude));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        NetUtil.sendToServer("searchParking", searchParkingMessage, mainActivityHandler);
    }
//oncamerachangelisener
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation.getAMapException().getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点
                Log.i("MainActivity","get location "+aMapLocation.getLatitude()+"  "+aMapLocation.getLongitude());
            }
        }
        else{
            Toast.makeText(this,"获取定位信息失败",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        Bundle data = intent.getExtras();
        userAccount = data.getString("userAccount");
        setContentView(R.layout.activity_main);
        mapView = (MapView) findViewById(R.id.map);

        nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

        // 构建地图
        mapView.onCreate(savedInstanceState);
        init();
        AMapEx aMapEx = new AMapEx(this, aMap);
        aMapEx.setRotateWithSensor(true);
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMarkerClickListener(this);



        //构建侧边栏
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mActivityList));
        mDrawerList.setOnItemClickListener(
                new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        try {
                            Intent intent = new Intent(MainActivity.this, Class.forName(mActivityClassList[position]));
                            startActivity(intent);
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                        mDrawerLayout.closeDrawer(mDrawerList);
                    }
                }
        );


        //构建websocket
        try {
            GlobalArgs.webClient=new ExampleClient( new URI( "ws://"+GlobalArgs.HOSTNAME+":8080/ParkServer/android/WebsocketAction" ), new Draft_17(),mainActivityHandler );

            GlobalArgs.webClient.connectBlocking();
            JSONObject wsLoginJson=new JSONObject();
            wsLoginJson.put("op", "login");


            Log.i("MainActivity", "GlobalArgs.userAccount:" + userAccount);


             wsLoginJson.put("account", userAccount);
             Log.i("MainActivity", "wsLoginJson:" + wsLoginJson.toString());
             GlobalArgs.webClient.send(wsLoginJson.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
    // 初始化AMap对象
    private void init() {


            aMap = mapView.getMap();
            aMap.setLocationSource(this);
            UiSettings aMapSetting=aMap.getUiSettings();
            aMapSetting.setZoomControlsEnabled(false);//设置显示地图默认的缩放按钮

            aMapSetting.setMyLocationButtonEnabled(true);// 是否显示定位按钮
            aMap.setMyLocationEnabled(true);// 是否可触发定位并显示定位层
            aMapSetting.setCompassEnabled(true);//设置指南针
            aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);




    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationManagerProxy == null) {
            mLocationManagerProxy = LocationManagerProxy.getInstance(this);
            //此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            //注意设置合适的定位时间的间隔，并且在合适时间调用removeUpdates()方法来取消定位请求
            //在定位结束后，在合适的生命周期调用destroy()方法
            //其中如果间隔时间为-1，则定位只定一次
            mLocationManagerProxy.requestLocationData(
                    LocationProviderProxy.AMapNetwork, 500, 1, this);
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destroy();
        }
        mLocationManagerProxy = null;
    }



    //弃用区
    @Override
    protected void onResume() {
        super.onResume();
        // 必须回调MapView的onResume()方法
        mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        // 必须回调MapView的onPause()方法
        mapView.onPause();


        if (mLocationManagerProxy != null) {
            mLocationManagerProxy.removeUpdates(this);
            mLocationManagerProxy.destory();
        }
        mLocationManagerProxy = null;
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 必须回调MapView的onSaveInstanceState()方法
        mapView.onSaveInstanceState(outState);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 必须回调MapView的onDestroy()方法
        mapView.onDestroy();
    }
    @Override
    public void onMapLoaded() {
        AMapEx aMapEx = new AMapEx(this, aMap);
        aMapEx.setRotateWithSensor(true);
    }



    @Override
    public void onLocationChanged(Location location) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }


    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);





    }

    @Override
    public boolean onMarkerClick(final Marker marker) {


        String str=marker.getTitle();
        if(str==null)
        {
            return false;
        }

        int index=Integer.valueOf(marker.getTitle());

        Intent toParkDetailIntent=new Intent(MainActivity.this,ParkDetailActivity.class);

        try {
            toParkDetailIntent.putExtra("parkDetailJsonString", receiveParksJA.get(index).toString());
        } catch (JSONException e) {
            Log.e("MainActivity","put parkdetailString into toParkDetailIntent fail");
            e.printStackTrace();
        }

        startActivity(toParkDetailIntent);
        return true;
    }


}

